import 'package:flutter/cupertino.dart';
import 'dart:ui' as ui;

class GradientTabIndicator extends Decoration {
  const GradientTabIndicator({
    this.borderRadius,
    required this.colors,
    this.stops,
    this.width = 30,
    this.height = 3,
  });

  /// The color and weight of the horizontal line drawn below the selected tab.
  final BorderRadius? borderRadius;
  final List<Color> colors;
  final List<double>? stops;
  final double height;
  final double width;

  @override
  _ColorPainter createBoxPainter([VoidCallback? onChanged]) {
    return _ColorPainter(this, onChanged);
  }
}

class _ColorPainter extends BoxPainter {
  _ColorPainter(this.decoration, VoidCallback? onChanged) : super(onChanged);

  final GradientTabIndicator decoration;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size!;
    final Paint paint = Paint();
    paint.shader = ui.Gradient.linear(
      ui.Offset((configuration.size!.width - decoration.width) / 2 + rect.left, configuration.size!.height),
      ui.Offset((configuration.size!.width + decoration.width) / 2 + rect.left, configuration.size!.height - decoration.height),
      decoration.colors,
      decoration.stops,
      TileMode.clamp,
      null,
    );
    canvas.drawRRect(
      RRect.fromLTRBAndCorners(
        (configuration.size!.width - decoration.width) / 2 + rect.left,
        configuration.size!.height,
        (configuration.size!.width + decoration.width) / 2 + rect.left,
        configuration.size!.height - decoration.height,
        topLeft: decoration.borderRadius?.topLeft ?? Radius.zero,
        topRight: decoration.borderRadius?.topRight ?? Radius.zero,
        bottomLeft: decoration.borderRadius?.bottomLeft ?? Radius.zero,
        bottomRight: decoration.borderRadius?.bottomRight ?? Radius.zero,
      ),
      paint,
    );
  }
}
